/* 
 * File:   GameStatus.cpp
 * Author: jose
 * 
 * Created on March 30, 2012, 7:19 PM
 */

#include "GameStatus.h"
#include <iostream>

GameStatus::GameStatus() : gameBoard(9, PLAYER_NONE) {
    currState = STATE_NULL;
    nextState = STATE_INTRO;
    numberOfPlayers = 0;
    winnerPlayer = PLAYER_NONE;
}

GameStatus::GameStatus(const GameStatus& orig) {
}

GameStatus::~GameStatus() {
}

bool GameStatus::setPlayerAtPosition(player player, int position) {
    gameBoard[position] = player;
    return true;
}

GameStatus::player GameStatus::getWinner() {
    return winnerPlayer;
}

bool GameStatus::isGameFinished() {
    bool gameFinished = true;
    player winner = PLAYER_NONE;
    
    //horizontal
    if(gameBoard[0] == gameBoard[1] && gameBoard[0] == gameBoard[2]  && gameBoard[0] != PLAYER_NONE)
    {
        winner = gameBoard[0];
    }
    else if(gameBoard[3] == gameBoard[4] && gameBoard[3] == gameBoard[5]  && gameBoard[3] != PLAYER_NONE)
    {
        winner = gameBoard[3];
    }
    else if(gameBoard[6] == gameBoard[7] && gameBoard[6] == gameBoard[8]  && gameBoard[6] != PLAYER_NONE)
    {
        winner = gameBoard[6];
    }
    //vertical
    else if(gameBoard[0] == gameBoard[3] && gameBoard[0] == gameBoard[6]  && gameBoard[0] != PLAYER_NONE)
    {
        winner = gameBoard[0];
    }
    else if(gameBoard[1] == gameBoard[4] && gameBoard[1] == gameBoard[7]  && gameBoard[1] != PLAYER_NONE)
    {
        winner = gameBoard[1];
    }
     else if(gameBoard[2] == gameBoard[5] && gameBoard[2] == gameBoard[8]  && gameBoard[2] != PLAYER_NONE)
    {
        winner = gameBoard[2];
    }
    //diagonal
    else if(gameBoard[0] == gameBoard[4] && gameBoard[0] == gameBoard[8]  && gameBoard[0] != PLAYER_NONE)
    {
        winner = gameBoard[0];
    }
    else if(gameBoard[2] == gameBoard[4] && gameBoard[2] == gameBoard[6]  && gameBoard[2] != PLAYER_NONE)
    {
        winner = gameBoard[2];
    }
    
    //no winner yet ???
    if(winner == PLAYER_NONE){
        //tie ??
        for (std::vector<GameStatus::player>::iterator Iter = gameBoard.begin(); Iter < gameBoard.end(); Iter++) {
        if (*Iter == PLAYER_NONE) {
            gameFinished = false; //no tie, still playing
        }
    }
    }
    else
    {
        winnerPlayer = winner;
        std::cout<< "We have a winner!!!! => " << winnerPlayer;
    }


    return gameFinished;
}

void GameStatus::setNextState(gameStates newState) {
    //If the user doesn't want to exit
    if (nextState != STATE_QUIT) {
        //Set the next state
        nextState = newState;
    }

}

GameStatus::gameStates GameStatus::getNewState() {
    //Change the current state ID
    currState = nextState;
    //NULL the next state ID
    nextState = STATE_NULL;

    return currState;
}

std::vector<GameStatus::player> GameStatus::getGameBoard() {
    return gameBoard;
}

bool GameStatus::isPositionEmpty(int position) {
    return gameBoard[position] == PLAYER_NONE;
}